import { routerRedux } from 'dva/router'
import modelExtend from 'dva-model-extend'
import { getCaptcha, login } from 'services/login'
import tokenHandler from 'utils/tokenHandler'
import { pageModel } from './common'

export default modelExtend(pageModel, {
  namespace: 'login',

  state: {
    captchaImg: '',
  },

  subscriptions: {
    // setup ({ dispatch, history }) {
    //   history.listen((location) => {
    //     if (location.pathname === '/login') {
    //       dispatch({
    //         type: 'getcaptcha',
    //       })
    //     }
    //   })
    // },
    setup ({ dispatch }) {
      dispatch({ type: 'getcaptcha' })
    },
  },

  effects: {
    * login ({ payload }, { put, call, select }) {
      const { code, data, msg } = yield call(login, payload)
      const { locationQuery } = yield select(_ => _.app)
      if (code === 0) {
        const { from } = locationQuery
        tokenHandler.setSessionByKey('token', data.token)
        yield put({ type: 'app/query' })
        if (from && from !== '/login') {
          // yield put(routerRedux.push(from))
          yield put(routerRedux.push(from))
        } else {
          yield put(routerRedux.push('/dashboard'))
        }
      } else {
        throw { message: msg, code }
      }
    },


    * getcaptcha ({ payload = {} }, { put, call }) {
      const data = yield call(getCaptcha)
      if (data) {
        yield put({
          type: 'updateModalState',
          payload: {
            captchaImg: data,
          },
        })
      } else {
        throw data
      }
    },
  },

  reducers: {
    updateModalState (state, { payload }) {
      return { ...state, ...payload }
    },

  },
})
